/*
 * Copyright (c) 2012, marco.tamburelli@gmail.com
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met: 
 * 
 * 1. Redistributions of source code must retain the above copyright notice, this
 *    list of conditions and the following disclaimer. 
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution. 
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 * 
 * The views and conclusions contained in the software and documentation are those
 * of the authors and should not be interpreted as representing official policies, 
 * either expressed or implied, of the CometMI Project.
 */
package org.cometmi.gwt.server.async;

import java.io.IOException;

import javax.servlet.AsyncContext;
import javax.servlet.AsyncEvent;
import javax.servlet.AsyncListener;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.google.gwt.user.client.rpc.SerializationException;

/**
 * @author marco.tamburelli@gmail.com
 */
public abstract class AsyncManager<T>
{
	static protected Logger logger = Logger.getLogger(AsyncManager.class);

	private AsyncContext asyncCtx;
	private AsyncListener asyncListener;

	private boolean active;

	protected AsyncManager(HttpServletRequest request, HttpServletResponse response)
	{
		this.active = true;

		this.asyncCtx = request.startAsync(request, response);
		this.asyncListener = new AsyncListener()
		{
			@Override
			public void onTimeout(AsyncEvent e) throws IOException
			{
				/*
				 * It's not tested in any servlet container, however I make the
				 * assumption that in case of timeout, this is the first method
				 * which will be fired.
				 */
				logger.error("[AsyncManager] timeout");
			}

			@Override
			public void onStartAsync(AsyncEvent e) throws IOException
			{}

			@Override
			public void onError(AsyncEvent e) throws IOException
			{
				/*
				 * It's not tested in any servlet container, however I make the
				 * assumption that in case of an error, this is the first method
				 * which will be fired. Note that in case of timeout this method
				 * could be fired, however it seems that the provided throwable
				 * is null.
				 */
				logger.error("[AsyncManager] error: ", e.getThrowable());
			}

			@Override
			public void onComplete(AsyncEvent e) throws IOException
			{
				AsyncManager.this.active = false;
			}
		};

		this.asyncCtx.addListener(this.asyncListener, request, response);
	}

	/**
	 * Sets the timeout for the awaiting response.
	 * 
	 * @param timeout
	 */
	public void setTimeout(long timeout)
	{
		this.asyncCtx.setTimeout(timeout);
	}

	/**
	 * This method should be invoked when the async procedure has terminated
	 * successfully.
	 * 
	 * @param returnValue The method return value
	 * @throws SerializationException
	 * @throws IOException
	 */
	public abstract void doCompleteForSuccess(T returnValue) throws SerializationException, IOException;

	/**
	 * This method should be invoked when the async procedure has terminated
	 * with an exception, or however with wrong result.
	 * 
	 * @param exception
	 * @throws SerializationException
	 * @throws IOException
	 */
	public abstract void doCompleteForFailure(Throwable exception) throws SerializationException, IOException;

	/**
	 * This method should be called in implementation of both methods
	 * {@link AsyncManager#doCompleteForSuccess(Object)} and
	 * {@link AsyncManager#doCompleteForFailure(Throwable)}.
	 */
	protected void doComplete()
	{
		this.asyncCtx.complete();
	}

	/**
	 * This method return <code>true</code> if the asych context has not yet
	 * completed or failed.
	 * 
	 * @return <code>true</code> or <code>false</code>.
	 */
	public boolean isActive()
	{
		return this.active;
	}
}
